﻿using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEditor.ProjectWindowCallback;
using UnityEngine;

public class CreateLuaClass
{
    static string tempPath = "Assets/Editor/Template/";
    static string filePath = "Assets/Lua/FaceCenter/";

    [MenuItem("GameObject/UIPageCtrl", false, 10)]
    public static void CreatNewPageCtrl()
    {
        ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0,
        ScriptableObject.CreateInstance<CreateLuaAsset>(), 
        filePath + "Ctrl/NewCtrl.lua", null, tempPath + "TempCtrl.txt");
    }

    [MenuItem("GameObject/UIPageView", false, 10)]
    public static void CreatNewPageView()
    {
        ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0,
        ScriptableObject.CreateInstance<CreateLuaAsset>(),
        filePath + "View/NewView.lua", null, tempPath + "TempView.txt");
    }
}

public class CreateLuaAsset : EndNameEditAction
{
    public override void Action(int instanceId, string pathName, string resourceFile)
    {
        Object o = CreateScriptAssetFromTemplate(pathName, resourceFile);
        ProjectWindowUtil.ShowCreatedAsset(o);
    }

    public Object CreateScriptAssetFromTemplate(string pathName, string resourceFile)
    {
        StreamReader streamReader = new StreamReader(resourceFile);
        string text = streamReader.ReadToEnd(); streamReader.Close();

        string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(pathName);
        text = Regex.Replace(text, "@ClassName", fileNameWithoutExtension);
        CreateScriptAction(ref text);

        string fullPath = Path.GetFullPath(pathName);
        StreamWriter streamWriter = new StreamWriter(fullPath, false, new UTF8Encoding());

        streamWriter.Write(text); streamWriter.Close();
        AssetDatabase.ImportAsset(pathName);
        return AssetDatabase.LoadAssetAtPath(pathName, typeof(Object));
    }

    public virtual void CreateScriptAction(ref string text) { }
}